from datetime import datetime
import os
import requests

class GiteeAPI:
    def __init__(self, token):
        self.token = token
        self.base_url = "https://gitee.com/api/v5"

    def get_issues(self, owner, repo):
        """获取仓库的 Issues 列表"""
        url = f"{self.base_url}/repos/{owner}/{repo}/issues"
        params = {"access_token": self.token}
        response = requests.get(url, params=params)
        response.raise_for_status()
        return response.json()

    def get_pull_requests(self, owner, repo):
        """获取仓库的 Pull Requests 列表"""
        print(owner,repo)
        url = f"{self.base_url}/repos/{owner}/{repo}/pulls"
        params = {"access_token": self.token}
        response = requests.get(url, params=params)
        response.raise_for_status()
        return response.json()

    def generate_daily_report(self, owner, repo):
        """生成每日进展的 Markdown 文件"""
        issues = self.get_issues(owner, repo)
        prs = self.get_pull_requests(owner, repo)

        # 文件名：<repo_name>_<YYYY-MM-DD>.md
        date = datetime.now().strftime("%Y-%m-%d")
        file_name = f"reports/{repo}_{date}.md"
        os.makedirs("reports", exist_ok=True)

        # 写入 Markdown 文件
        with open(file_name, "w", encoding="utf-8") as f:
            f.write(f"# Daily Report: {repo} ({date})\n\n")
            f.write("## Issues\n")
            for issue in issues:
                f.write(f"- [{issue['title']}]({issue['html_url']})\n")

            f.write("\n## Pull Requests\n")
            for pr in prs:
                f.write(f"- [{pr['title']}]({pr['html_url']})\n")

        print(f"Report generated: {file_name}")
        return file_name
    
    def get_latest_release(self, owner, repo):
        api_url = f"{self.base_url}/repos/{owner}/{repo}/releases/latest"
        headers = {"Authorization": f"token {self.token}"}

        try:
            response = requests.get(api_url, headers=headers)
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 404:
                print("No releases found for the repository.")
                return None
            else:
                print(f"Failed to fetch release info: {response.status_code}")
                return None
        except Exception as e:
            print(f"Error occurred while fetching release info: {e}")
            return None

